package apis

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-resty/resty/v2"
	"net/http"
	"strconv"
	"strings"
	"sync"
	"time"
	"zorm-learn/app/util"
)

var Routers = make([]func(*gin.RouterGroup), 0)

type UriParams struct {
	UriParam1 string `uri:"path1"`
	UriParam2 string `uri:"path2"`
	UriParam3 string `uri:"path3"`
	UriParam4 string `uri:"path4"`
}

func init() {
	Routers = append(Routers, func(group *gin.RouterGroup) {
		group.Any("/api/:path1/:path2/:path3/:path4", handler)
		group.Any("/api/:path1/:path2/:path3", handler)
		group.Any("/api/:path1/:path2", handler)
		group.Any("/api/:path1", handler)
		group.Any("/api/merge", mergeHandler)
	})
}

func mergeHandler(context *gin.Context) {
	client := resty.New()
	urlMap := make(map[string]string)
	dataMap := util.NewSafeMap()
	if err := context.ShouldBindJSON(&urlMap); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var wg sync.WaitGroup
	for key, uri := range urlMap {
		wg.Add(1)
		go queryDataApi(key, uri, dataMap, &wg, client)
	}
	wg.Wait()

	context.JSON(200, dataMap.GetMap())

}

func queryDataApi(key string, uri string, m *util.SafeMap, s *sync.WaitGroup, client *resty.Client) {
	defer s.Done()

	fmt.Println(uri)
	resp, err := client.R().Get("http://localhost:8080/api/v1/api/aaa/bbb/ccc/" + uri)
	if err != nil {
		m.Store(key, "")
		return
	}
	body := resp.Body()
	data := make(map[string]any)
	err = json.Unmarshal(body, &data)
	m.Store(key, data)
}

func handler(context *gin.Context) {
	uri := context.Request.RequestURI
	fmt.Println(uri)
	//	split := strings.Split(uri, "v1/api")
	method := context.Request.Method
	fmt.Println(method)
	client := resty.New()
	// Make a GET request
	if http.MethodGet == method {
		milli := time.Now().UnixMilli()
		resp, err := client.R().Get("https://www.baidu.com")
		if err != nil {
			util.HandlerApiError(context, err, resp.StatusCode())
			util.MainCtx.Logger.Error("E-R-R:" + err.Error())
			return
		}
		body := resp.Body()
		m := make(map[string]any)
		err = json.Unmarshal(body, &m)
		cost := time.Now().UnixMilli() - milli
		formatInt := strconv.FormatInt(cost, 10)
		util.MainCtx.Logger.Info("cost is :" + formatInt)
		context.JSON(resp.StatusCode(), util.Success(body))
	}
}
func __handler(context *gin.Context) {
	uri := context.Request.RequestURI
	fmt.Println(uri)
	split := strings.Split(uri, "v1/api")
	method := context.Request.Method
	fmt.Println(method)
	client := resty.New()
	// Make a GET request
	if http.MethodGet == method {
		resp, err := client.R().Get("http://" + util.MainCtx.OriginalApisHost + split[1])
		if err != nil {
			util.HandlerApiError(context, err, resp.StatusCode())
			return
		}
		body := resp.Body()
		m := make(map[string]any)
		err = json.Unmarshal(body, &m)
		if err != nil {
			util.HandlerApiError(context, err, resp.StatusCode())
			return
		}
		context.JSON(resp.StatusCode(), m)
	}
}
